package net.easyjava.framework.web.filter;

import net.easyjava.tools.lang.StringTools;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 解决跨域的问题
 * Created by wxnacy on 16/11/16.
 */
public class CORSFilter implements Filter {
    private String domain;
    private String maxAge;
    /**
     * 跨域加载
     * @param filterConfig
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("CORSFilter.init");
        String dom = filterConfig.getInitParameter("domain");
        if(StringTools.isEmpty(dom)){
            this.domain = "*";
        }else{
            this.domain = dom;
        }

        this.maxAge = filterConfig.getInitParameter("maxAge");

    }

    /**
     *
     * @param req
     * @param res
     * @param chain
     */
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        System.out.println("CORSFilter.doFilter");
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
//        if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
        response.setHeader("Access-Control-Allow-Origin", domain);
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        response.setHeader("Access-Control-Max-Age", maxAge);//30 min
//        }
        chain.doFilter(req,res);
    }

    /**
     */
    @Override
    public void destroy() {
        System.out.println("CORSFilter.destroy");
    }

    public void setDomain(String domain) {
        System.out.println("CORSFilter.setDomain");
        this.domain = domain;
    }
}
